package com.mkuspis.moviebrowser.preferences;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;

import java.util.Calendar;

public class PreferencesEditor {

    private SharedPreferences sPref;
    private SharedPreferences.Editor editor;

    private final static String SAVED_PREFERENCES = "saved_time";
    private final static String DAY = "day";
    private final static String HOUR = "hour";

    private final Context context;

    public PreferencesEditor(final Context context) {
        this.context = context;
    }

    @SuppressLint("CommitPrefEdits")
    private void SetWorkingPrefState(final Integer listID) {
        sPref = context.getSharedPreferences(SAVED_PREFERENCES + listID.toString(), 0);
        editor = sPref.edit();
    }

    private void save(final int hourOfUpdate, final int day) {
        editor.putInt(HOUR, hourOfUpdate);
        editor.putInt(DAY, day);
        editor.commit();
    }

    private int readTime() {
        return sPref.getInt(HOUR, 0);
    }

    private int readDay() {
        return sPref.getInt(DAY, 0);
    }

    public boolean isUpdateNeeded(final Integer listID) {
        SetWorkingPrefState(listID);
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_YEAR);
        int days;
        if ((days = day - readDay()) > 2) return true;
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        if (days == 1) {
            hours += 24;
        }
        boolean result = (readTime() + 6) < hours;
        return result;
    }

    public void updateNow(final Integer listID) {
        SetWorkingPrefState(listID);
        Calendar calendar = Calendar.getInstance();
        int hours = calendar.get(Calendar.HOUR_OF_DAY);
        int day = calendar.get(Calendar.DAY_OF_YEAR);
        save(hours, day);
    }
}